﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PMPUtils.Form;
using PMPUtils.Goals;

namespace PMP.Goals
{
    public partial class AddGoalDetail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.Authenticate(Session, Response);

            if (!IsPostBack)
            {
                txtGoal.Text = Request.Params["PARENT_ID"];
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (!CheckRequiredFields())
            {
                Messenger.Show(Response, "Please fill all required fields.");
                return;
            }

            String goal = txtGoal.Text.Trim();
            String task = txtTask.Text.Trim();
            String dueDate = calDueDate.SelectedDate.ToString("yyyy-MM-dd");

            try
            {
                if (GoalDetailsOperator.IsGoalDetailExists(goal, task))
                {
                    Messenger.Show(Response, "The task was already added.");
                    return;
                }
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            try
            {
                GoalDetailsOperator.AddNewGoalDetail(goal, task, String.Empty, dueDate);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Goal detail added successfully.");

            Close();
        }

        private bool CheckRequiredFields()
        {
            bool fieldsChecked = true;

            if (txtTask.Text.Trim().Equals(String.Empty))
            {
                fieldsChecked = false;
            }

            return fieldsChecked;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Close()
        {
            PopupForm addGoalDetails = new PopupForm(Response);
            addGoalDetails.Close();
        }
    }
}
